﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Wicresoft.Framework.Organization;
using Attendences.Framework.BusinessLogic;
using Attendences.Framework.Entity;
using System.IO;
using Wicresoft.Common;
using System.Collections.Generic;

public partial class Page_AttendencesDetail : BaseAuthenticationPage
{
    string show = "";
    public int AttendID
    {
        get
        {
            if (Request.QueryString["ID"] != null)
                return int.Parse(Request.QueryString["ID"]);
            return 0;
        }
    }
    public bool Manage
    {
        get
        {
            if (!string.IsNullOrEmpty(Request["Manage"]) && Request["Manage"].ToLower() == "false")
                return false;
            return true;
        }
    }
    protected DataTable AttendItemList
    {
        get
        {
            if (ViewState["AttendItemList"] == null)
                ViewState["AttendItemList"] = new DataTable();
            return ViewState["AttendItemList"] as DataTable;
        }
        set
        {
            ViewState["AttendItemList"] = value;
        }
    }
    protected DataTable AttendAll
    {
        get
        {
            if (ViewState["AttendAll"] == null)
                ViewState["AttendAll"] = new DataTable();
            return ViewState["AttendAll"] as DataTable;
        }
        set
        {
            ViewState["AttendAll"] = value;
        }
    }
    protected DataTable AttendenceUserList
    {
        get
        {
            if (ViewState["AttendenceUserList"] == null)
                ViewState["AttendenceUserList"] = new DataTable();
            return ViewState["AttendenceUserList"] as DataTable;
        }
        set
        {
            ViewState["AttendenceUserList"] = value;
        }
    }

    protected DataTable AttendenceDateUser
    {
        get
        {
            if (ViewState["AttendenceDateUser"] == null)
                ViewState["AttendenceDateUser"] = new DataTable();
            return ViewState["AttendenceDateUser"] as DataTable;
        }
        set
        {
            ViewState["AttendenceDateUser"] = value;
        }
    }
    protected override void OnInit(EventArgs e)
    {
        lbtnExport.Click += new EventHandler(lbtnExport_Click);
        //btnAddUser.Click += new EventHandler(btnAddUser_Click);
        base.OnInit(e);
    }

    //void btnAddUser_Click(object sender, EventArgs e)
    //{
    //    if (txtNewUserNames.Text != string.Empty && txtNewUserNames.Text.IndexOf(";")!= -1)
    //    {
    //        string[] UserIDs = txtNewUserIDs.Text.Split(';');
    //        string[] UserNames = txtNewUsers.Text.Split(';');
    //        string[] UserDisplayNames = txtNewUserNames.Text.Split(';');
    //        for (int i = 0; i < UserIDs.Length; i++)
    //        {
    //            Guid userID = new Guid(UserIDs[i]);
    //            string userName = UserNames[i];
    //            string userDisplayName = UserDisplayNames[i];
    //            AttendenceUser user = new AttendenceUser(AttendID, userID);
    //            user.UserDisplayName = userDisplayName;
    //            user.UserName = userName;
    //            user.Save();
    //        }
    //    }
    //    else if (txtNewUserNames.Text != null)
    //    {
    //        AttendenceUser user = new AttendenceUser(AttendID,new Guid(txtNewUserIDs.Text));
    //        user.UserDisplayName = txtNewUserNames.Text;
    //        user.UserName = txtNewUsers.Text;
    //        user.Save();
    //    }
    //    else
    //    {
    //        ClientScript.RegisterStartupScript(GetType(), "NoUserSelected", "<script>alert('请选择需要添加的用户');</script>");
    //        return;
    //    }
    //    AttendenceUserList = BLAttendences.GetAttendenceUser(string.Format("{0} ={1}", AttendenceItem.SQLCOL_ATTENDENCEID, AttendID));
    //    AttendAll = DataAccess.Select(typeof(View_Attend_All), string.Format("{0} ={1}", AttendenceItem.SQLCOL_ATTENDENCEID, AttendID));
    //    BindData();
    //}

    protected void lbtnExport_Click(object sender, EventArgs e)
    {
        string str = string.Empty;
        User[] Users = null;
        OtherUser[] oUsers = null;
        Property[] props = null;
        string[] PropNames = new string[] { "OfficePhone", "Mobile", "HomePhone" };
        if (AttendenceUserIDs != string.Empty)
        {
            if (AttendenceUserIDs.IndexOf(";") == -1)
            {
                Guid UserID = new Guid(AttendenceUserIDs);

                Users = OrganizationHelper.GetUserInfoList(new Guid[] { UserID });
                props = OrganizationHelper.GetPropertyInfoListByUsers(new Guid[] { UserID }, PropNames);
            }
            else
            {
                string[] strUserIds = AttendenceUserIDs.Split(';');
                //throw new Exception(AttendenceUserIDs.ToString());
                Guid[] UserIDs = new Guid[strUserIds.Length];
                for (int i = 0; i < strUserIds.Length; i++)
                {
                    UserIDs[i] = new Guid(strUserIds[i]);
                }
                Users = OrganizationHelper.GetUserInfoList(UserIDs);
                props = OrganizationHelper.GetPropertyInfoListByUsers(UserIDs, PropNames);
            }
        }
        else if (AttendenceOtherUserIDs != string.Empty)
        {
            oUsers = BLOtherUser.getUserList(string.Format("ID in ('{0}')", AttendenceOtherUserIDs.Replace(";", "','")));
        }
        else
        {
            string script = "<script>alert('尚没有值班人员勾选！！！');</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "Close", script);
            return;
        }
        foreach (RepeaterItem ri in rptItemList.Items)
        {
            Label labUser = ri.FindControl("labUser") as Label;
            if (labUser.Text == "未选定")
            {
                string script = "<script>alert('尚有部分值班时间没有值班人员！！！');</script>";
                ClientScript.RegisterStartupScript(this.GetType(), "Close", script);
                return;
            }
        }
        if ((Users != null || oUsers != null) && AttendAll.Rows.Count > 0)
        {
            Response.Clear();
            string filename = "值班人员联系方式";
            StringWriter sw = new StringWriter();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(filename) + ".xls");
            Response.ContentType = "application/ms-excel";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            DataTable dtAttendDate = new DataTable();
            dtAttendDate.Columns.Add("AttendTime", typeof(string));
            dtAttendDate.Columns.Add("AttendTimeStart", typeof(string));
            dtAttendDate.Columns.Add("AttendTimeEnd", typeof(string));
            dtAttendDate.Columns.Add("AttendDate", typeof(string));
            dtAttendDate.Columns.Add("AttendPlace", typeof(string));
            dtAttendDate.Columns.Add("AttendDESC", typeof(string));
            Hashtable ht = new Hashtable();
            foreach (DataRow dr in AttendAll.Rows)
            {
                if (!ht.ContainsKey(dr[View_Attend_All.SQLCOL_ATTENDDATE].ToString() + dr[View_Attend_All.SQLCOL_ATTENDTIMESTART].ToString() + dr[View_Attend_All.SQLCOL_ATTENDTIMEEND].ToString()))
                {
                    DataRow drName = dtAttendDate.NewRow();
                    drName["AttendTime"] = Convert.ToDateTime(dr[View_Attend_All.SQLCOL_ATTENDTIMESTART]).ToString("yyyy-MM-dd HH:mm至") + Convert.ToDateTime(dr[View_Attend_All.SQLCOL_ATTENDTIMEEND]).ToString("yyyy-MM-dd HH:mm");
                    drName["AttendTimeStart"] = dr[View_Attend_All.SQLCOL_ATTENDTIMESTART];
                    drName["AttendTimeEnd"] = dr[View_Attend_All.SQLCOL_ATTENDTIMEEND];
                    drName["AttendDate"] = dr[View_Attend_All.SQLCOL_ATTENDDATE];
                    drName["AttendPlace"] = dr[View_Attend_All.SQLCOL_PLACE];
                    drName["AttendDESC"] = dr[View_Attend_All.SQLCOL_DESCRIPTION];
                    dtAttendDate.Rows.Add(drName);
                    ht.Add(dr[View_Attend_All.SQLCOL_ATTENDDATE].ToString() + dr[View_Attend_All.SQLCOL_ATTENDTIMESTART].ToString() + dr[View_Attend_All.SQLCOL_ATTENDTIMEEND].ToString(), dr[View_Attend_All.SQLCOL_ATTENDDATE].ToString() + dr[View_Attend_All.SQLCOL_ATTENDTIMESTART].ToString() + dr[View_Attend_All.SQLCOL_ATTENDTIMEEND].ToString());
                }
            }
            string ExcelRow = string.Format(@"<table style=""font-size:18px;font-family:楷体_GB2312"" align=""center"">
                                                    <tr align=""center"">
                                                        <td colspan=""5"" style=""border:1px solid black;font-weight:bold"">
                                                            {0}
                                                        </td>
                                                    </tr>
                                                    <tr align=""center"">
                                                        <td colspan=""5"" style=""border:1px solid black;border-top-width:0px;font-weight:bold"">
                                                            值班地点：{1}
                                                        </td>
                                                    </tr>
                                                    <tr align=""center"">
                                                    <td style=""border:1px solid black;border-top-width:0px;font-weight:bold"">值班时间</th>
                                                    <td style=""border:1px solid black;border-top-width:0px;font-weight:bold"">值班人员</th>
                                                    <td style=""border:1px solid black;border-top-width:0px;font-weight:bold"">办公室电话</th>
                                                    <td style=""border:1px solid black;border-top-width:0px;font-weight:bold"">家庭电话</th>
                                                    <td style=""border:1px solid black;border-top-width:0px;font-weight:bold"">手机</th>
                                                    </tr>
                                                    ", AttendAll.Rows[0][View_Attend_All.SQLCOL_NAME], AttendAll.Rows[0][View_Attend_All.SQLCOL_PLACE]);
            foreach (DataRow _dr in dtAttendDate.Rows)
            {
                DataRow[] drs = AttendAll.Select(string.Format("{0}='{1}' and {2} = '{3}' and {4} = '{5}'", View_Attend_All.SQLCOL_ATTENDDATE, _dr["AttendDate"], View_Attend_All.SQLCOL_ATTENDTIMESTART, _dr["AttendTimeStart"], View_Attend_All.SQLCOL_ATTENDTIMEEND, _dr["AttendTimeEnd"]));
                string OldAttendTime = string.Empty;
                foreach (DataRow dr in drs)
                {
                    ExcelRow += "<tr>";
                    if (OldAttendTime != Convert.ToDateTime(dr[View_Attend_All.SQLCOL_ATTENDTIMESTART]).ToString("yyyy-MM-dd HH:mm至") + Convert.ToDateTime(dr[View_Attend_All.SQLCOL_ATTENDTIMEEND]).ToString("yyyy-MM-dd HH:mm"))
                    {
                        ExcelRow += string.Format(@"<td rowspan=""{0}"" valign=""middle""  style=""border:1px solid black;border-top-width:0px;"" align=""center"">{1}</td>
                                                  ", drs.Length, Convert.ToDateTime(dr[View_Attend_All.SQLCOL_ATTENDTIMESTART]).ToString("yyyy-MM-dd HH:mm至") + Convert.ToDateTime(dr[View_Attend_All.SQLCOL_ATTENDTIMEEND]).ToString("yyyy-MM-dd HH:mm"));
                        OldAttendTime = Convert.ToDateTime(dr[View_Attend_All.SQLCOL_ATTENDTIMESTART]).ToString("yyyy-MM-dd HH:mm至") + Convert.ToDateTime(dr[View_Attend_All.SQLCOL_ATTENDTIMEEND]).ToString("yyyy-MM-dd HH:mm");
                    }

                    if (dr["UserType"].ToString() == UserType.Portal.ToString())
                    {
                        User user = null;
                        foreach (User u in Users)
                        {
                            if (u.Name == dr["UserName"].ToString())
                            {
                                user = u;
                            }
                        }
                        if (user != null)
                        {
                            ExcelRow += string.Format(@" 
                                        <td style=""border:1px solid black;border-top-width:0px;border-left-width:0px"">{0}
                                        </td>
                                        <td style=""border:1px solid black;border-top-width:0px;border-left-width:0px"">{1}
                                        </td>
                                        <td style=""border:1px solid black;border-top-width:0px;border-left-width:0px"">{2}
                                        </td>
                                        <td style=""border:1px solid black;border-top-width:0px;border-left-width:0px"">{3}
                                        </td>
                                      ", user.DisplayName, getProperty(props, user.ID, "OfficePhone"), getProperty(props, user.ID, "HomePhone"), getProperty(props, user.ID, "Mobile"));
                        }
                    }
                    else if (dr["UserType"].ToString() == UserType.Other.ToString())
                    {
                        OtherUser user = null;
                        foreach (OtherUser u in oUsers)
                        {
                            if (u.ID.ToString() == dr["UserID"].ToString())
                            {
                                user = u;
                            }
                        }
                        if (user != null)
                        {
                            ExcelRow += string.Format(@" 
                                        <td style=""border:1px solid black;border-top-width:0px;border-left-width:0px"">{0}
                                        </td>
                                        <td style=""border:1px solid black;border-top-width:0px;border-left-width:0px"">{1}
                                        </td>
                                        <td style=""border:1px solid black;border-top-width:0px;border-left-width:0px"">{2}
                                        </td>
                                        <td style=""border:1px solid black;border-top-width:0px;border-left-width:0px"">{3}
                                        </td>
                                      ", user.DisplayName, user.Phone, user.Phone, user.Mobile);
                        }
                    }
                    ExcelRow += "</tr>";
                }
            }
            sw.Write(ExcelRow);
            sw.Write(string.Format(@"<tr><td colspan=""5"" style=""border:none;text-align:left"">{0}</td></tr>", AttendAll.Rows[0][View_Attend_All.SQLCOL_DESCRIPTION].ToString()));
            sw.Write("<table>");
            sw.Close();
            Response.Write(sw);
            Response.End();
        }
    }
    private string getProperty(Property[] propertys, Guid UserID, string PropertyName)
    {
        foreach (Property p in propertys)
        {
            if (p.NodeID == UserID && p.Name == PropertyName)
            {
                return p.Data.ToString();
            }

        }
        return string.Empty;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        this.Title = "值班详细清单";
        this.UseTabber = true;
        if (!IsPostBack)
        {
            //AttendenceUserList = BLAttendences.GetAttendenceUser(string.Format("{0} ={1}", AttendenceItem.SQLCOL_ATTENDENCEID, AttendID));
            AttendAll = DataAccess.Select(typeof(View_Attend_All), string.Format("{0} ={1}", AttendenceItem.SQLCOL_ATTENDENCEID, AttendID));
            BindData();
        }

        tdEdit.Visible = Manage;
        tdDelete.Visible = Manage;

        Attendence att = new Attendence(AttendID);
        att.Load();
        if (att.IsShutDown)
        {
            //lbtnShutDowm.Visible = false;
            //td1.Visible = false;
            //cancalShutDown.Visible = true;
            //td3.Visible = true;
            //thAttendencer.Visible = false;
        }
        else
        {
            //lbtnShutDowm.Visible = true;
            //td1.Visible = true;
            //cancalShutDown.Visible = false;
            //td3.Visible = false;
            //thAttendencer.Visible = true;
        }
        //dlAttendUsers.DataSource = AttendenceUserList;
        //dlAttendUsers.DataBind();
    }

    protected void rptItemList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {

        Label labUser = e.Item.FindControl("labUser") as Label;

    }

    protected void lbtnDelete_Click(object sender, EventArgs e)
    {
        //首先将AttendID存进数组里，再调用DeleteAttendenceList删除操作
        BLAttendences.DeleteAttendencesList(new int[] { AttendID });
        ClientScript.RegisterStartupScript(this.GetType(), "Delete", "<script>parent.location.href = parent.location.href</script>");
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        BindData();
        ClientScript.RegisterStartupScript(this.GetType(), "Finish", "<script>parent.document.getElementById('ctl00$ListToolBarPlaceHolder$btnRefresh').click();</script>");
    }
    private string AttendenceUserIDs
    {
        get
        {
            if (ViewState["AttendenceUserIDs"] == null)
                ViewState["AttendenceUserIDs"] = string.Empty;
            return ViewState["AttendenceUserIDs"].ToString();
        }
        set
        {
            ViewState["AttendenceUserIDs"] = value;
        }
    }
    private string AttendenceOtherUserIDs
    {
        get
        {
            if (ViewState["AttendenceOtherUserIDs"] == null)
                ViewState["AttendenceOtherUserIDs"] = string.Empty;
            return ViewState["AttendenceOtherUserIDs"].ToString();
        }
        set
        {
            ViewState["AttendenceOtherUserIDs"] = value;
        }
    }
    private void BindData()
    {
        string usercount = AttendenceUserList.Rows.Count.ToString();
        //throw new Exception(AttendenceUserList.Rows.Count.ToString());
        Attendence attendence = new Attendence(AttendID);
        attendence.Load();

        ltTitle.Text = "值班表单";
        ltDescription.Text = attendence.Description;
        ltCreateTime.Text = attendence.CreateTime.ToString("yyyy年MM月dd日");
        ltName.Text = attendence.Name;
        ltPlace.Text = attendence.Place;

        ltTitle2.Text = "值班详情";
        ltName2.Text = attendence.Name;
        ltPlace2.Text = attendence.Place;
        //ltCreateTime2.Text = attendence.CreateTime.ToString("yy-MM-dd");

        //从当前选定的表Attendence的ID通过AttendenceID返回当前选定的AttendenceItem表中的内容
        DataTable dtType = DataAccess.SelectAll(typeof(AttendenceType));
        DataTable dt = BLAttendences.GetAttendenceItem(string.Format("{0} = {1}", AttendenceItem.SQLCOL_ATTENDENCEID, AttendID));
        foreach (DataRow item in dt.Rows)
        {
            DataRow[] dr2s = dtType.Select("ID='" + item["Remark"].ToString()+"'");
            if (dr2s.Length > 0)
            {
                item["remark"] = dr2s[0]["Name"].ToString();
            
            }
        }
        AttendItemList = dt.Clone();
        DataRow[] drs = dt.Select("1=1", "AttendDate");
        foreach (DataRow dr in drs)
        {
            AttendItemList.ImportRow(dr);
        }
        rptItemList.DataSource = AttendItemList;
        rptItemList.DataBind();
        //throw new Exception(show);
        foreach (RepeaterItem ri in rptItemList.Items)
        {
            DataRow drItem = AttendItemList.Rows[ri.ItemIndex];
            Guid id = new Guid(drItem[AttendenceItem.SQLCOL_ID].ToString());

            AttendenceDate ad = new AttendenceDate();
            ad.AttendenceItemID = id;
            Label labUser = ri.FindControl("labUser") as Label;
            string lab = "";
            AttendenceDateUser = BLAttendences.GetAttendenceDateUser(string.Format("{0}='{1}' order by OrderNum", AttendenceDate.SQLCOL_ATTENDENCEITEMID, id));
            foreach (DataRow ar in AttendenceDateUser.Rows)
            {
                if (lab == string.Empty)
                {
                    lab = ar["UserDisplayName"].ToString();

                }
                else
                {
                    lab = lab + ";" + ar["UserDisplayName"].ToString();
                }
                if (ar["UserType"].ToString() == UserType.Portal.ToString())
                {
                    if (AttendenceUserIDs.IndexOf(ar["UserID"].ToString().Trim()) == -1)
                    {
                        if (AttendenceUserIDs == string.Empty)
                        {
                            AttendenceUserIDs += ar["UserID"].ToString();
                        }
                        else if (AttendenceUserIDs.IndexOf(ar["UserID"].ToString()) < 0)
                        {
                            AttendenceUserIDs += ";" + ar["UserID"].ToString();
                        }
                    }
                }
                else
                {
                    if (AttendenceOtherUserIDs.IndexOf(ar["UserID"].ToString().Trim()) == -1)
                    {
                        if (AttendenceOtherUserIDs == string.Empty)
                        {
                            AttendenceOtherUserIDs += ar["UserID"].ToString();
                        }
                        else if (AttendenceOtherUserIDs.IndexOf(ar["UserID"].ToString()) < 0)
                        {
                            AttendenceOtherUserIDs += ";" + ar["UserID"].ToString();
                        }
                    }
                }
            }
            if (lab == string.Empty)
            {
                lab = "未选定";
            }
            labUser.Text = lab;
        }
    }

    //protected void lbtnSave_Click(object sender, EventArgs e)
    //{
    //    foreach (RepeaterItem ri in rptItemList.Items)
    //    {
    //        DataRow drItem = AttendItemList.Rows[ri.ItemIndex];
    //        Guid id = new Guid(drItem[AttendenceItem.SQLCOL_ID].ToString());

    //        AttendenceDate ad = new AttendenceDate();
    //        ad.AttendenceItemID = id;
    //        CheckBoxList ddlUser = ri.FindControl("ddlUser") as CheckBoxList;
    //        ddlUser.RepeatColumns = 4;
    //        Label labUser = ri.FindControl("labUser") as Label;
    //        string lab = "";

    //        for (int i = 0; i < ddlUser.Items.Count; i++)
    //        {
    //            if (ddlUser.Items[i].Selected)
    //            {
    //                ad.UserID = new Guid(ddlUser.Items[i].Value);
    //                foreach (DataRow dr in AttendenceUserList.Rows)
    //                {
    //                    if ((Guid)dr["UserID"] == ad.UserID && ad.UserID != Guid.Empty)
    //                    {
    //                        ad.UserDisplayName = dr["UserDisplayName"].ToString();

    //                        if (lab == string.Empty)
    //                        {
    //                            lab = ad.UserDisplayName;
    //                        }
    //                        else
    //                        {
    //                            lab = lab + ";" + ad.UserDisplayName;
    //                        }
    //                        ad.Save();
    //                    }
    //                }
    //            }
    //            else
    //            {
    //                ad.UserID = new Guid(ddlUser.Items[i].Value);
    //                ad.Delete();
    //            }
    //        }

    //        if (lab == string.Empty)
    //        {
    //            lab = "未选定";
    //        }
    //        labUser.Text = lab;
    //    }
    //    string script = "<script>alert('保存成功!');refreshParent();</script>";
    //    ClientScript.RegisterStartupScript(this.GetType(), "Close", script);
    //}

    protected void lbtnShutDown_Click(object sender, EventArgs e)
    {
        Attendence attendence = new Attendence(AttendID);
        attendence.Load();
        if (attendence.IsShutDown == false)
        {
            attendence.IsShutDown = true;
            attendence.Save();
        }
        else
        {
            string script = "<script>alert('该值班安排已发布过!')</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "Close", script);
        }
        string s = "<script>refreshParent();</script>";
        ClientScript.RegisterStartupScript(this.GetType(), "refresh", s);
    }

    protected void cancalShutDown_Click(object sender, EventArgs e)
    {
        Attendence attendence = new Attendence(AttendID);
        attendence.Load();
        if (attendence.IsShutDown == true)
        {
            attendence.IsShutDown = false;
            attendence.Save();
        }
        else
        {
            string script = "<script>alert('该值班安排未发布过!');</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "Close", script);
        }
        string s = "<script>refreshParent();</script>";
        ClientScript.RegisterStartupScript(this.GetType(), "refresh", s);
    }
}

